package com.xckj.ibox.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;

import com.tencent.bugly.crashreport.CrashReport;
import com.xckj.ibox.R;
import com.xckj.ibox.bean.AgreementBean;
import com.xckj.ibox.bean.BannerBean;
import com.xckj.ibox.bean.HomeGoodsBean;
import com.xckj.ibox.bean.HomeMenuBean;
import com.xckj.ibox.bean.NoticeBean;
import com.xckj.ibox.databinding.FragmentHomeBinding;
import com.xckj.ibox.event.LoginStateEvent;
import com.xckj.ibox.framework.BaseFragment;
import com.xckj.ibox.global.Constant;
import com.xckj.ibox.iview.IHomeView;
import com.xckj.ibox.presenter.HomePresenter;
import com.xckj.ibox.ui.activity.BrowserActivity;
import com.xckj.ibox.ui.activity.LoginActivity;
import com.xckj.ibox.ui.adapter.HomeGoodsAdapter;
import com.xckj.ibox.ui.adapter.HomeMenuAdapter;
import com.xckj.ibox.utils.AndroidUtil;
import com.xckj.ibox.utils.LoadImageUtil;
import com.xckj.ibox.utils.SpUtil;
import com.xckj.ibox.view.CustomDialog;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.DrawableIndicator;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ChenYao
 * @Describe: 首页
 * @Date: 2023/6/14 16:57
 */
public class HomeFragment extends BaseFragment<FragmentHomeBinding> implements IHomeView {
    private HomePresenter homePresenter;
    private HomeMenuAdapter homeMenuAdapter;
    private HomeGoodsAdapter homeGoodsAdapter;
    private int goodsType = 0;
    private List<HomeMenuBean> mMenuBeans;
    private List<HomeGoodsBean.DataBean> homeGoodBeans;

    @Override
    protected boolean isStatusBarDarkFont() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        homePresenter = new HomePresenter(this);
        homePresenter.getAgreement();
        homePresenter.getBanner();
        homePresenter.getHomeMenu();
        homePresenter.getNotice();
        if (TextUtils.isEmpty(SpUtil.getString(requireActivity(), Constant.IS_FIRST))) {
            initAgreementDialog();
        }
        initHomeMenu();
        getHomeGoods();
        loginState();
        initGoods();
        setListener();
    }


    private void initNotice(List<NoticeBean> noticeBeans) {
        dataBinding.vfNotice.removeAllViews();
        for (int i = 0; i < noticeBeans.size(); i++) {
            @SuppressLint("InflateParams") View view = LayoutInflater.from(requireActivity()).inflate(R.layout.item_notice, null);
            TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
            tvTitle.setText(noticeBeans.get(i).title);
            final int index = i;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showMsg(noticeBeans.get(index).title);
                }
            });
            dataBinding.vfNotice.addView(view);
        }
        if (dataBinding.vfNotice.getChildCount() > 1) {
            dataBinding.vfNotice.startFlipping();
        } else {
            dataBinding.vfNotice.stopFlipping();
        }

    }

    private void initAgreementDialog() {
        CustomDialog customDialog = new CustomDialog(requireActivity(), R.style.CustomDialogStyle);
        Window window = customDialog.getWindow();
        WindowManager.LayoutParams localLayoutParams = window.getAttributes();
        localLayoutParams.gravity = Gravity.BOTTOM;
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setPadding(0, 0, 0, 0);
        localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        localLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        customDialog.getWindow().setAttributes(localLayoutParams);
        customDialog.setCancelClickListener(new CustomDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                System.exit(0);
                customDialog.dismiss();
            }
        });
        customDialog.setSureOnclickListener(new CustomDialog.OnSureClickListener() {
            @Override
            public void onSureClick() {
                SpUtil.put(requireActivity(), Constant.IS_FIRST, "first");
                CrashReport.initCrashReport(requireActivity(), Constant.BUGLY_APP_ID, false);
                customDialog.dismiss();
            }
        });
        customDialog.setLookAgreementClickListenerOne(new CustomDialog.OnLookAgreementClickListenerOne() {
            @Override
            public void onLookAgreementClickListener() {
                BrowserActivity.start(requireActivity(), SpUtil.getString(requireActivity(), Constant.Agreement.AGREEMENT_1));
            }
        });
        customDialog.setLookAgreementClickListenerTwo(new CustomDialog.OnLookAgreementClickListenerTwo() {
            @Override
            public void onLookAgreementClickListener() {
                BrowserActivity.start(requireActivity(), SpUtil.getString(requireActivity(), Constant.Agreement.AGREEMENT_3));
            }
        });
        customDialog.show();
    }

    private void getHomeGoods() {
        homePresenter.getHomeGoods(Constant.PAGE, Constant.PAGE_SIZE, goodsType);
    }

    private void loginState() {
        if (AndroidUtil.loginState()) {
            dataBinding.rlLogin.setVisibility(View.GONE);
        } else {
            dataBinding.rlLogin.setVisibility(View.VISIBLE);
        }
    }

    @SuppressLint("NonConstantResourceId")
    private void setListener() {
        dataBinding.llSearch.setOnClickListener(view -> {
            if (AndroidUtil.loginState()) {
                BrowserActivity.start(requireActivity(), Constant.H5Address.SEARCH_URL);
            } else {
                startActivity(new Intent(requireActivity(), LoginActivity.class));
            }
        });
        dataBinding.ivMessage.setOnClickListener(view -> {
            if (AndroidUtil.loginState()) {
                BrowserActivity.start(requireActivity(), Constant.H5Address.MESSAGE_URL);
            } else {
                startActivity(new Intent(requireActivity(), LoginActivity.class));
            }
        });
        dataBinding.rlLogin.setOnClickListener(view -> {
            startActivity(new Intent(requireActivity(), LoginActivity.class));
        });
        dataBinding.rgType.setOnCheckedChangeListener((radioGroup, i) -> {
            switch (i) {
                case R.id.rb_new_release:
                    goodsType = 0;
                    getHomeGoods();
                    break;
                case R.id.rb_hot_arrange:
                    goodsType = 1;
                    getHomeGoods();
                    break;
                default:
                    break;
            }
        });
    }

    private void initBanner(List<BannerBean> bannerBean) {
        dataBinding.banner.addBannerLifecycleObserver(this);
        dataBinding.banner.setIndicator(new DrawableIndicator(getContext(), R.mipmap.icon_banner_normal, R.mipmap.icon_banner_selected));
        BannerImageAdapter bannerImageAdapter = new BannerImageAdapter<BannerBean>(bannerBean) {
            @Override
            public void onBindView(BannerImageHolder holder, BannerBean data, int position, int size) {
                LoadImageUtil.loadImage(data.image, holder.imageView, R.drawable.comm_null_image);
            }

        };
        dataBinding.banner.setAdapter(bannerImageAdapter);
        OnBannerListener bannerListener = (data, position) -> {
            if (AndroidUtil.loginState()) {
                String id = homeGoodBeans.get(position).id;
                BrowserActivity.start(requireActivity(), String.format(Constant.H5Address.GOODS_DETAILS_URL, id));
            } else {
                startActivity(new Intent(requireActivity(), LoginActivity.class));
            }
        };
        dataBinding.banner.setOnBannerListener(bannerListener);
    }

    private void initHomeMenu() {
        dataBinding.homeMenu.setLayoutManager(new GridLayoutManager(requireActivity(), 4));
        homeMenuAdapter = new HomeMenuAdapter();
        homeMenuAdapter.setOnItemClickListener((view, position) -> {
            if (AndroidUtil.loginState()) {
                if (TextUtils.isEmpty(mMenuBeans.get(position).url)) {
                    showMsg("该功能正在开发中");
                    return;
                }
                BrowserActivity.start(requireActivity(), mMenuBeans.get(position).url);
            } else {
                startActivity(new Intent(requireActivity(), LoginActivity.class));
            }

        });
        dataBinding.homeMenu.setAdapter(homeMenuAdapter);
    }

    private void initGoods() {
        dataBinding.goodsList.setLayoutManager(new GridLayoutManager(requireActivity(), 2));
        homeGoodsAdapter = new HomeGoodsAdapter();
        homeGoodsAdapter.setOnItemClickListener((view, position) -> {
            if (AndroidUtil.loginState()) {
                String id = homeGoodBeans.get(position).id;
                BrowserActivity.start(requireActivity(), String.format(Constant.H5Address.GOODS_DETAILS_URL, id));
            } else {
                startActivity(new Intent(requireActivity(), LoginActivity.class));
            }
        });
        dataBinding.goodsList.setAdapter(homeGoodsAdapter);
    }

    @Override
    public void getBannerSuccess(List<BannerBean> bannerBeanList) {
        initBanner(bannerBeanList);
    }


    @Override
    public void getHomeMenuSuccess(List<HomeMenuBean> menuBeans) {
        mMenuBeans = menuBeans;
        homeMenuAdapter.setHomeMenuData(menuBeans);
    }

    @Override
    public void getHomeGoodsSuccess(HomeGoodsBean goodsBean) {
        homeGoodBeans = new ArrayList<>(goodsBean.data);
        homeGoodsAdapter.setHomeGoodsData(homeGoodBeans);
    }

    @Override
    public void getAgreement(AgreementBean agreementBean) {
        SpUtil.put(requireActivity(), Constant.Agreement.AGREEMENT_1, agreementBean.pingtai_xieyi);
        SpUtil.put(requireActivity(), Constant.Agreement.AGREEMENT_2, agreementBean.yinsi_xieyi);
        SpUtil.put(requireActivity(), Constant.Agreement.AGREEMENT_3, agreementBean.yonghu_xieyi);
    }

    @Override
    public void getNotice(List<NoticeBean> noticeBeans) {
        initNotice(noticeBeans);
    }

    @Override
    public void failed(String message) {
        showMsg(message);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshLoginState(LoginStateEvent loginStateEvent) {
        loginState();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
